package com.sdry.product.prod.service;


import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.reflect.TypeToken;
import com.google.gson.Gson;
import com.sdry.basic.entity.ContainerStare;
import com.sdry.basic.entity.Material;
import com.sdry.basic.entity.ProductionStation;
import com.sdry.common.BaseAPIMessageTypeEnum;
import com.sdry.exception.BizException;
import com.sdry.exception.CommonEnum;
import com.sdry.product.prehangingline.entity.PreHangingLine;
import com.sdry.product.prehangingline.mapper.PreHangingLineMapper;
import com.sdry.product.prod.entity.LacquerInto;
import com.sdry.product.prod.entity.ProductHandleOut;
import com.sdry.product.prod.entity.ResultAppList;
import com.sdry.product.prod.mapper.LacquerIntoMapper;
import com.sdry.product.prod.mapper.ProductHandleOutMapper;
import com.sdry.product.sorting.entity.SortFrame;
import com.sdry.product.sorting.mapper.SortReceivingDetailMapper;
import com.sdry.product.sorting.mapper.SortReceivingMapper;
import com.sdry.product.sorting.mapper.SortingStockMapper;
import com.sdry.untils.CustomUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.List;
import java.util.zip.ZipException;

/**
 * (LacquerInto)表服务实现类
 *
 * @author makejava
 * @since 2020-03-04 13:57:35
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class LacquerIntoServiceImpl implements LacquerIntoService {
    @Resource
    private LacquerIntoMapper lacquerIntoDao;

    @Resource
    private PreHangingLineMapper preHangingLineMapper;

    @Resource
    private ProductHandleOutMapper productHandleOutMapper;

    @Resource
    private SortingStockMapper sortingStockMapper;

    @Resource
    private SortReceivingDetailMapper sortReceivingDetailMapper;


    @Resource
    private SortReceivingMapper sortReceivingMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param laintoId 主键
     * @return 实例对象
     */
    @Override
    public LacquerInto queryById(Long laintoId) {
        return this.lacquerIntoDao.queryById(laintoId);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit 查询条数
     * @return 对象列表
     */
    @Override
    public List<LacquerInto> queryAllByLimit(int offset, int limit) {
        return this.lacquerIntoDao.queryAllByLimit(offset, limit);
    }


    /**
     * 修改数据
     *
     * @param lacquerInto 实例对象
     * @return 实例对象
     */
    @Override
    public LacquerInto update(LacquerInto lacquerInto) {
        this.lacquerIntoDao.update(lacquerInto);
        return this.queryById(lacquerInto.getLaintoId());
    }

    /**
     * 通过主键删除数据
     *
     * @param laintoId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long laintoId) {
        return this.lacquerIntoDao.deleteById(laintoId) > 0;
    }

    /**
     * 分页查询
     * @param lacquerInto 实例对象
     * @return 实例对象
     */
    @Override
    public List<LacquerInto> queryLacquerIntoPage(LacquerInto lacquerInto) {
        List<LacquerInto> lacquerIntoList = lacquerIntoDao.queryLacquerIntoPage(lacquerInto);
        return lacquerIntoList;
    }

    /**
     * 总数
     * @param lacquerInto 实例对象
     * @return 实例对象
     */
    @Override
    public Long queryLacquerIntoTotal(LacquerInto lacquerInto) {
        return lacquerIntoDao.queryLacquerIntoTotal(lacquerInto);
    }

    @Override
    public void bindingLacquerInto2(String json, String userId) {
        Gson gson = new Gson();
        ResultAppList<Material> materialResultAppList = gson.fromJson(json, ResultAppList.class);
        List<Material> materialList = gson.fromJson(materialResultAppList.getList().toString(), new TypeToken<List<Material>>() {
        }.getType());
        for (Material material : materialList) {
            LacquerInto lacquerial = new LacquerInto();
            //喷涂工位编号
            lacquerial.setStationNumber(materialResultAppList.getPsnumber());
            String remark = "PT";
            Long stationId = preHangingLineMapper.queryContainerByNumber(materialResultAppList.getPsnumber(),remark);
            if (stationId == null) {
                throw new  BizException(BaseAPIMessageTypeEnum.A098.getName());
            }
            //喷涂工位
            lacquerial.setStationId(stationId);
            //产品ID
            lacquerial.setMaterielId(material.getMaId());
            //产品数量
            lacquerial.setQuantity(material.getQuantity());
            //喷涂要求
            lacquerial.setSprayingRequirements(material.getMaSprayingRequirements());
            //来源
            lacquerial.setSource(material.getRemark04());
            //挂架编号
            lacquerial.setPylonsId(0L);
            //挂线工位编号
            lacquerial.setPylonsStationId(0L);
            //容器
            lacquerial.setContainerId(Long.parseLong(material.getPsId()));
            //操作人员
            lacquerial.setCreateBy(userId);
            //备注
            lacquerial.setRemark(material.getOldPsnumber());

            //判断这个工位在倒线过程中是否被使用
            QueryWrapper<LacquerInto> queryWrapper05 = new QueryWrapper<>();
            queryWrapper05.eq("station_id", stationId)
                    .eq("materiel_id",material.getMaId())
                    .eq("status", 0L);
            List<LacquerInto> lacquerIntoList = lacquerIntoDao.selectList(queryWrapper05);
            //如果库存没有新增，如果库存有，改变数量
            /*if (lacquerIntoList.size() > 0){
                LacquerInto lacquer05 = new LacquerInto();
                Long quantity = lacquerIntoList.get(0).getQuantity() + material.getQuantity();
                lacquer05.setQuantity(quantity);
                int update = lacquerIntoDao.update(lacquer05, queryWrapper05);
                if(update <= 0){
                    throw new BizException(BaseAPIMessageTypeEnum.A095.getName());
                }
            }else {
                int insert = lacquerIntoDao.insert(lacquerial);
                if(insert <= 0){
                    throw new BizException(BaseAPIMessageTypeEnum.A095.getName());
                }
            }*/

            int insert = lacquerIntoDao.insert(lacquerial);
            if(insert <= 0){
                throw new BizException(BaseAPIMessageTypeEnum.A095.getName());
            }

            //绑定数量
            Long bindingQuantity = material.getQuantity();
            //更改前处理区状态来源ID
            if (material.getRemark04().equals("QCL")){
                CustomUtil.updatePreTreatment(material, stationId, bindingQuantity, productHandleOutMapper);
            }else if (material.getRemark04().equals("FJ")){
                //更改分拣区状态来源ID
                CustomUtil.updateSortingArea(bindingQuantity,userId, material, stationId, sortingStockMapper, sortReceivingDetailMapper);
            }else if (material.getRemark04().equals("WZZ")){

                //容器原本的数量
                Long quantity = sortReceivingDetailMapper.queryContainerStareQuantity(material.getPsId(), material.getMaId());
                //绑定数量和库存数量对比
                if (quantity.equals(bindingQuantity)){
                    //相等时，删除容器装载表
                    Integer effect = sortReceivingDetailMapper.deleteContainerStareQuantity(material.getPsId(), material.getMaId());
                    if(effect <= 0){
                        throw new BizException(BaseAPIMessageTypeEnum.A095.getName());
                    }
                    //更改容器装载记录表状态
                    Integer effect2 = sortReceivingDetailMapper.updateTransitOrderRecordStatus(material.getPsId(),material.getMaId());
                    if(effect2 <= 0){
                        throw new BizException(BaseAPIMessageTypeEnum.A095.getName());
                    }
                }else if (quantity < bindingQuantity) {
                    //绑定数量大于库存数量
                    throw new BizException(BaseAPIMessageTypeEnum.A096.getName());
                }else if (quantity > bindingQuantity) {
                    String remark21 = "PT";
                    //更改容器装载数量
                    Integer effect = sortReceivingDetailMapper.updateContainerStareQuantity(material.getPsId(),material.getMaId(),quantity - bindingQuantity,userId,remark21);
                    if(effect <= 0){
                        throw new BizException(BaseAPIMessageTypeEnum.A095.getName());
                    }
                }
            }
        }
    }


    @Override
    public void bindingLacquerInto(String json, String userId) {
        Gson gson = new Gson();
        List<ResultAppList<Material>> resultAppList = gson.fromJson(json, new TypeToken<List<ResultAppList<Material>>>() {}.getType());
        for (ResultAppList<Material> materialResultAppList : resultAppList) {
            List<Material> list = materialResultAppList.getList();
            //判断这个工位在倒线过程中是否被使用
            QueryWrapper<LacquerInto> queryWrapper05 = new QueryWrapper<>();
            queryWrapper05.eq("station_id", materialResultAppList.getNewPsId())
                    .eq("status", 0L);
            List<LacquerInto> lacquerIntoList05 = lacquerIntoDao.queryList(Long.parseLong(materialResultAppList.getNewPsId()),0L);
            if (lacquerIntoList05.size() > 0){
                throw new  BizException(BaseAPIMessageTypeEnum.A099.getName());
            }
            for (Material material : list) {
                LacquerInto lacquerial = new LacquerInto();
                //喷涂旧工位编号
                lacquerial.setRemark(materialResultAppList.getPsnumber());
                //新工位
                lacquerial.setStationNumber(materialResultAppList.getNewPsnumber());

                Long stationId = lacquerIntoDao.queryWorkstation(materialResultAppList.getNewPsnumber());
                if (stationId == null) {
                    throw new  BizException(BaseAPIMessageTypeEnum.A098.getName());
                }

                //新工位ID
                lacquerial.setStationId(stationId);
                //产品ID
                lacquerial.setMaterielId(material.getMaId());
                //产品数量
                lacquerial.setQuantity(material.getQuantity());
                //喷涂要求
                lacquerial.setSprayingRequirements(material.getMaSprayingRequirements());
                //来源
                lacquerial.setSource("YG");
                //挂架编号
                lacquerial.setPylonsId(0L);
                //挂线工位编号
                lacquerial.setPylonsStationId(0L);
                //容器ID
                lacquerial.setContainerId(Long.parseLong(materialResultAppList.getPsId()));
                //操作人员
                lacquerial.setCreateBy(userId);
                lacquerIntoDao.insert(lacquerial);
                //更改预挂线状态
                QueryWrapper<PreHangingLine> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("station_id",materialResultAppList.getPsId())
                        .eq("station_number",materialResultAppList.getPsnumber())
                        .eq("materiel_id",material.getMaId())
                        .eq("status",0L);
                PreHangingLine preHangingLine = new PreHangingLine();
                preHangingLine.setStatus("2");
                preHangingLine.setUpdateBy(userId);
                preHangingLine.setUpdateDate(new Timestamp(System.currentTimeMillis()));
                preHangingLineMapper.update(preHangingLine,queryWrapper);
            }
        }
    }

    @Override
    public List<ProductionStation> queryWorkstation(String permissionType) {
        return lacquerIntoDao.queryWorkstation2(permissionType);
    }

    @Override
    public List<ResultAppList<Material>> queryPtMateriel(String[] containerNumber) {
        List<Material> materialList = lacquerIntoDao.queryPtMateriel(containerNumber);
        return CustomUtil.QueryResultChange(materialList);
    }


}